package com.wj.tool.common.utils.paging;


import com.wj.tool.common.utils.CollectionUtils;

import java.util.List;
import java.util.function.Supplier;

/**
 * <Description>
 *
 * @author wangchao
 * @version 1.0
 * @date 2020/12/09
 */
public class PageUtil {

    private PageUtil(){}

    public static <T,S> QueryResults<S> pageResult(Paging paging, List<T> doList, QueryResults<S> queryResults, Supplier<S> target){
        PageInfo<T> pageInfo = new PageInfo<>(doList);
        paging.setTotalNumber((int) pageInfo.getTotal());
        paging.setTotalPages(pageInfo.getPages());
        queryResults.setPaging(paging);
        if (CollectionUtils.isEmpty(doList)){
            return queryResults;
        }
        queryResults.setResults(ListCopyUtils.copyListProperties(doList,target));
        return queryResults;
    }

    /**
     * 自定义分页
     * @param pageNum
     * @param pageSize
     * @param list
     * @param <T>
     * @return
     */
    public static <T> QueryResults<T> listToPage(int pageNum, int pageSize, List<T> list) {
        QueryResults<T> results = new QueryResults<>();
        List<T> subList;
        int limit = (pageNum - 1) * pageSize;
        int size = list.size();
        int totalPage = getTotalPage(pageSize, size);
        if (pageNum == totalPage) {
            subList = list.subList(limit, size);
        } else {
            int end = limit + pageSize;
            subList = list.subList(limit, end);
        }
        results.setResults(subList);
        Paging paging = new Paging();
        paging.setTotalNumber(size);
        paging.setTotalPages(totalPage);
        paging.setPageSize(pageSize);
        paging.setPageNumber(pageNum);
        results.setPaging(paging);
        return results;
    }

    /**
     * 根据总条数获取总页数
     * @param pageSize
     * @param totalSize
     * @return
     */
    public static int getTotalPage(int pageSize, int totalSize) {
        int totalPage = 0;
        if (totalSize % pageSize == 0) {
            totalPage = totalSize / pageSize;
        } else {
            totalPage = totalSize / pageSize + 1;
        }
        return totalPage;
    }
}
